from django.conf import settings

from .models import UserProfile
from django.contrib.auth import get_user_model

User = get_user_model()  # 获取用户模型

from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from django.db.models import Max
from rest_framework import serializers


class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    profile = UserProfile

    @classmethod
    def get_token(cls, user):
        token = super(MyTokenObtainPairSerializer, cls).get_token(user)
        # 添加额外信息
        token['username'] = user.username
        token['id'] = user.id
        # 存入个人信息中的是否认证成功字段
        try:
            token['userprofile_id'] = user.profile.id
            token['avatar'] = settings.MEDIA_PREFIX + user.profile.avatar.name
            token['nickname'] = user.profile.nickname
        except Exception as e:
            token['userprofile_id'] = None
            token['nickname'] = None
            print(e)
        return token

    def validate(self, attrs):
        data = super().validate(attrs)

        refresh = self.get_token(self.user)

        # data['refresh'] = str(refresh)
        # data['access'] = str(refresh.access_token)
        # data.pop('refresh')
        data['username'] = refresh['username']
        data['id'] = refresh['id']
        data['avatar'] = refresh['avatar']
        data['userprofile_id'] = refresh['userprofile_id']
        data['nickname'] = refresh['nickname']
        return data



class UserProfileSerializer(serializers.ModelSerializer):

    class Meta:
        model = UserProfile
        # fields = '__all__'
        exclude = ('user', )

class UserProfileDetalSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserProfile
        fields = '__all__'
        # exclude = ('user',)
